package com.yl.zqy.service.impl.sys;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yl.zqy.entity.sys.SysRoleMenu;
import com.yl.zqy.mapper.sys.SysRoleMenuMapper;
import com.yl.zqy.service.sys.SysRoleMenuService;
import com.yl.zqy.vo.user.AuthMenusByRole;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色菜单关系 服务实现类
 * </p>
 *
 * @author liang.yu
 * @since 2024-03-28
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {

    @Override
    public Boolean roleAuthorizeMenus(AuthMenusByRole auth) {
        LambdaQueryWrapper<SysRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleMenu::getRoleId, auth.getRoleId());
        baseMapper.delete(queryWrapper);
        List<SysRoleMenu> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(auth.getMenuId())) {
            auth.getMenuId().stream().forEach(item -> {
                SysRoleMenu eneity = new SysRoleMenu();
                eneity.setRoleId(auth.getRoleId());
                eneity.setMenuId(item);
                eneity.setCreator(StpUtil.getLoginIdAsString());
                eneity.setCreateDate(LocalDateTime.now());
                list.add(eneity);
            });
            return saveBatch(list);
        }
        return true;
    }

    @Override
    public List<String> getRoleByMenus(String roleId) {
        List<String> result = new ArrayList<>();
        LambdaQueryWrapper<SysRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleMenu::getRoleId, roleId);
        List<SysRoleMenu> sysRoleMenus = baseMapper.selectList(queryWrapper);
        sysRoleMenus.stream().forEach(item -> {
            result.add(item.getMenuId());
        });
        return result;
    }
}
